package id.net.iconpln.bb.client.view;

import id.net.iconpln.bb.client.service.MasterRPCService;
import id.net.iconpln.bb.client.service.MasterRPCServiceAsync;
import id.net.iconpln.bb.client.service.TransportRPCService;
import id.net.iconpln.bb.client.service.TransportRPCServiceAsync;
import id.net.iconpln.bb.client.tools.ComboRakorPembangkit;
import id.net.iconpln.bb.client.util.ClientModule;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.core.FastMap;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class PageBbApprovalPengajuanJadwal extends LayoutContainer{
	private Grid gridPemasok;
	private EditorGrid gridJadwal;
	private ListStore storePemasok, storeJadwal;
	private final MasterRPCServiceAsync serviceMaster = GWT.create(MasterRPCService.class);
	private final TransportRPCServiceAsync service = GWT.create(TransportRPCService.class);
	private Integer jml_gagal = 0, jml_sukses = 0;
	private ComboBox cboRakor;
	private TextField txtTglRakor, txtAgendaRakor;
	private TextField txtTglJadwal, txtEtdJadwal, txtEtaJadwal, txtVolJadwal, txtTransportir;
		
	@Override
	protected void onRender(Element parent, int index) {
		// TODO Auto-generated method stub
		super.onRender(parent, index);
		setLayout(new FitLayout());	
		storeJadwal = new ListStore();
		
		ContentPanel cp = new ContentPanel();  
	    cp.setHeaderVisible(false);
	    cp.setFrame(true);  
	    cp.setLayout(new RowLayout(Orientation.HORIZONTAL)); 
	    
	    ContentPanel cpLeft = new ContentPanel();
	    cpLeft.setHeaderVisible(false);
	    cpLeft.setLayout(new RowLayout(Orientation.VERTICAL));	
	    cpLeft.setBorders(false);
	    
	    FormLayout layout = new FormLayout();  
	    layout.setLabelWidth(120);  
	    FieldSet fieldSet = new FieldSet();  
	    fieldSet.setHeading("Data Rakor");  
	    fieldSet.setCollapsible(false);
	    fieldSet.setLayout(layout); 
	    
	    cboRakor = new ComboRakorPembangkit(Registry.get("idPltu").toString());
	    cboRakor.addSelectionChangedListener(new SelectionChangedListener<ModelData>() {
	    	@Override
	    	public void selectionChanged(SelectionChangedEvent<ModelData> se) {
	    		// TODO Auto-generated method stub
	    		txtTglRakor.setValue(se.getSelectedItem().get("tanggal"));
	    		txtAgendaRakor.setValue(se.getSelectedItem().get("agenda"));
	    		
	    		refreshPemasok();
	    	}
		});
	    fieldSet.add(cboRakor);
	    txtTglRakor = new TextField();
	    txtTglRakor.setFieldLabel("Tanggal");	 
	    txtTglRakor.setReadOnly(true);
	    fieldSet.add(txtTglRakor);
	    txtAgendaRakor = new TextField();
	    txtAgendaRakor.setFieldLabel("Agenda");	 
	    txtAgendaRakor.setReadOnly(true);
	    fieldSet.add(txtAgendaRakor);
	    
	    ContentPanel cpLeftUp = new ContentPanel();
	    cpLeftUp.setHeaderVisible(false);
	    cpLeftUp.setBorders(false);
	    cpLeftUp.add(fieldSet);
	    cpLeft.add(cpLeftUp, new RowData(1, .3));
	    
	    ContentPanel cpLeftDown = new ContentPanel();
	    cpLeftDown.setHeaderVisible(true);
	    cpLeftDown.setHeading("Data Pemasok");
	    cpLeftDown.setLayout(new RowLayout(Orientation.VERTICAL));	
	    cpLeftDown.setBorders(true);
	    
	    storePemasok = new ListStore();
		storePemasok.setMonitorChanges(true); 		
		
		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();  

	    ColumnConfig column = new ColumnConfig();
	    column = new ColumnConfig("pemasok", "Pemasok", 250);  
	    configs.add(column);
	    
	    column = new ColumnConfig("jumlah", "Jumlah", 50);  
	    configs.add(column);
	    
	    ColumnModel cm = new ColumnModel(configs);  
	    
	    gridPemasok= new Grid(storePemasok, cm);	
	    gridPemasok.addListener(Events.CellClick, new Listener<BaseEvent>() {            
            public void handleEvent(BaseEvent ge) {
            	getJadwalByPemasok();
            }
		});
	    
	    cpLeftDown.add(gridPemasok, new RowData(1,1));	   
	    cpLeft.add(cpLeftDown, new RowData(1, .7));
	    
	    cp.add(cpLeft, new RowData(.4, 1));
	    
	    ContentPanel cpRight = new ContentPanel();
	    cpRight.setHeaderVisible(false);
	    cpRight.setBorders(false);
	    cpRight.setLayout(new RowLayout(Orientation.VERTICAL));	
	    
	    ContentPanel cpRightUp = new ContentPanel();
	    cpRightUp.setHeaderVisible(false);
	    cpRightUp.setBorders(true);
	    cpRightUp.setLayout(new FitLayout());	
	    ToolBar tbJadwal = new ToolBar();
	    tbJadwal.add(new LabelToolItem("<b>Data Pengajuan Jadwal</b>"));
	    tbJadwal.add(new SeparatorToolItem());
	    
	    Button btnFilter = new Button("Approve", new SelectionListener<ButtonEvent>() {  
	        @Override  
	        public void componentSelected(ButtonEvent ce) {  
	        	jml_gagal = 0; jml_sukses = 0;
	        	for (int x=0 ; x < gridJadwal.getStore().getModels().size(); x++){
	        		String v = "";
	        		try{
	        			v = gridJadwal.getStore().getAt(x).get("approve").toString();
	        		}catch (Exception e) {
						v = "";
					}
	        		if (v.equals("true")){
	        			setApprovalJadwal(gridJadwal.getStore().getAt(x).get("no_jadwal").toString() , "2");
	        		}
	        		if ( x == gridJadwal.getStore().getModels().size() - 1){
	        			getJadwalByPemasok();        			
	        		}
	        	}
	        	
	        	refreshPemasok();
	        }  
	     });  
	    btnFilter.setIcon(IconHelper.createStyle("icon-contact-add"));
	    
	    tbJadwal.add(btnFilter);
	    
	    cpRightUp.setTopComponent(tbJadwal);
	    
	    storeJadwal.setMonitorChanges(true); 
	    
	    List<ColumnConfig> configsJadwal = new ArrayList<ColumnConfig>();  

	    ColumnConfig columnJadwal = new ColumnConfig();
	    CheckColumnConfig checkColumn = new CheckColumnConfig("approve", "Approve", 55); 
	    CheckBox cb = new CheckBox();
	    cb.setValue(true);
	    CellEditor checkBoxEditor = new CellEditor(cb);  
	    checkColumn.setEditor(checkBoxEditor);  
	    configsJadwal.add(checkColumn);  
	    
	    columnJadwal = new ColumnConfig("no_jadwal", "No Jadwal", 150);  
	    configsJadwal.add(columnJadwal);  
	    
	    columnJadwal = new ColumnConfig("no_pln_pjbb", "No Kontrak PJBB", 150);  
	    configsJadwal.add(columnJadwal); 
	    
	    columnJadwal = new ColumnConfig("status", "Status", 150);  
	    configsJadwal.add(columnJadwal);
	    
	    ColumnModel cmJadwal = new ColumnModel(configsJadwal);  
	    
	    gridJadwal = new EditorGrid(storeJadwal, cmJadwal);	
	    gridJadwal.getView().setEmptyText("Data Empty");  
	    gridJadwal.addListener(Events.CellClick, new Listener<BaseEvent>() {            
            public void handleEvent(BaseEvent ge){
            	txtTglJadwal.setValue(gridJadwal.getSelectionModel().getSelectedItem().get("tanggal"));
	    		txtEtdJadwal.setValue(gridJadwal.getSelectionModel().getSelectedItem().get("tgl_td"));
	    		txtEtaJadwal.setValue(gridJadwal.getSelectionModel().getSelectedItem().get("tgl_ta"));
	    		txtVolJadwal.setValue(gridJadwal.getSelectionModel().getSelectedItem().get("volume"));
	    		txtTransportir.setValue(gridJadwal.getSelectionModel().getSelectedItem().get("nama_transportir"));
            }
		});
	    cpRightUp.add(gridJadwal);
	    cpRight.add(cpRightUp, new RowData(1, .5));
	    
	    ContentPanel cpRightDown = new ContentPanel();
	    cpRightDown.setHeaderVisible(false);
	    cpRightDown.setBorders(false);
	    cpRightDown.setLayout(new FitLayout());	
	    	   
	    FormLayout layoutJadwal = new FormLayout();  
	    layoutJadwal.setLabelWidth(120);  
	    
	    FieldSet fieldSetJadwal = new FieldSet();  
	    fieldSetJadwal.setHeading("Detail Jadwal");  
	    fieldSetJadwal.setCollapsible(false);
	    fieldSetJadwal.setLayout(layoutJadwal); 
	    
	    txtTglJadwal = new TextField();
	    txtTglJadwal.setFieldLabel("Tanggal");	 
	    txtTglJadwal.setReadOnly(true);
	    fieldSetJadwal.add(txtTglJadwal);
	    txtEtdJadwal = new TextField();
	    txtEtdJadwal.setFieldLabel("ETD");	 
	    txtEtdJadwal.setReadOnly(true);
	    fieldSetJadwal.add(txtEtdJadwal);
	    txtEtaJadwal = new TextField();
	    txtEtaJadwal.setFieldLabel("ETA");	 
	    txtEtaJadwal.setReadOnly(true);
	    fieldSetJadwal.add(txtEtaJadwal);
	    txtVolJadwal = new TextField();
	    txtVolJadwal.setFieldLabel("Volume (Ton)");	 
	    txtVolJadwal.setReadOnly(true);
	    fieldSetJadwal.add(txtVolJadwal);	    
	    txtTransportir = new TextField();
	    txtTransportir.setFieldLabel("Transportir");	 
	    txtTransportir.setReadOnly(true);
	    fieldSetJadwal.add(txtTransportir);
	    cpRightDown.add(fieldSetJadwal);
	    
	    cpRight.add(cpRightDown, new RowData(1, .5));
	    
	    ContentPanel delimeter = new ContentPanel();
	    delimeter.setHeaderVisible(false);
	    delimeter.setWidth(10);
	    cp.add(delimeter, new FitData(5));
	    cp.add(cpRight, new RowData(.6, .95));
	    add(cp);		
	}
	
	private void getJadwalByPemasok(){
		Map mapParam = new FastMap();
	  	mapParam.put("no_pln_pjbb", "");
	  	mapParam.put("id_pltu", Registry.get("idPltu").toString());
	  	mapParam.put("id_pemasok", gridPemasok.getSelectionModel().getSelectedItem().get("id_pemasok"));
	  	mapParam.put("status", "");
	  
	  	service.getListPengendalian("PENGAJUAN_JADWAL", mapParam,new AsyncCallback<List<Map>>() {
	  		public void onFailure(Throwable caught) {
	  			GWT.log(caught.getMessage(), null);
	  		}

	  		public void onSuccess(List<Map> result) {	
		  		storeJadwal.removeAll();
	  		  	storeJadwal.add(ClientModule.setListBaseModelFromListMap(result));
	  		}
	  	});
	}
	
	private void setApprovalJadwal(String no_jadwal, String id_pltu){
		Map mapParam = new FastMap();
	  	mapParam.put("no_jadwal", no_jadwal);
	  	mapParam.put("no_rakor", cboRakor.getValue().get("no_rakor"));
	  	mapParam.put("id_rakor", cboRakor.getValue().get("id_rakor"));
	  	mapParam.put("id_pltu", Registry.get("idPltu").toString());
	  	mapParam.put("user", Registry.get("whoAmI").toString());
	  	mapParam.put("app_access", "WEB");
	  	mapParam.put("crud", "CREATE_BY_APPROVE");
	  
	  	service.insertPengendalianBB("JADWAL", mapParam,new AsyncCallback<List<Map>>() {
	  		public void onFailure(Throwable caught) {
	  			GWT.log(caught.getMessage(), null);
	  			jml_gagal++;
	  		}

	  		public void onSuccess(List<Map> result) {	
	  			jml_sukses++;
	  			getJadwalByPemasok();
	  		}
	  	});
	}
	
	private void refreshPemasok(){
		Map mapParam = new FastMap();
		mapParam.put("id_pltu", Registry.get("idPltu").toString());
		mapParam.put("no_rakor", cboRakor.getValue().get("no_rakor"));
		serviceMaster.getMaster("PEMASOK_BY_PLTU_RAKOR", mapParam, new AsyncCallback<List<Map>>() {
			public void onFailure(Throwable caught) {
				GWT.log(caught.getMessage(), null);
			}

			public void onSuccess(List<Map> result) {	
				storePemasok.removeAll();
				storePemasok.add(ClientModule.setListBaseModelFromListMap(result));
			}
		});		
	}
}
